import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class MetaRetriever {
	private double width;
	private double height;
	private double ulX;
	private double ulY;
	private double xScale;
	private double yScale;

	public MetaRetriever(String mapPath, String decoderPath) {
		boolean finished=false;
		try {
			FileWriter fstream = new FileWriter("c:\\tmpBat.bat");
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(decoderPath+ " -i "+ mapPath	+ " -o c:\\tmpMap.jpg -of jpg  -ulxy 0 0 -wh 1 1 > c:\\tmpMeta.txt");
			out.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		try {
			Process p= Runtime.getRuntime().exec("c:\\tmpBat.bat");
			p.waitFor();
		} catch (IOException e) {e.printStackTrace();}
		catch (InterruptedException e) {e.printStackTrace();}
		
		/*try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {}*/
		try {
			FileInputStream fstream = new FileInputStream("c:\\tmpMeta.txt");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null && finished==false) {
				if (strLine.contains("width:"))
					width=Double.parseDouble(strLine.replace("width:",""));
				if (strLine.contains("height:"))
					height=Double.parseDouble(strLine.replace("height:",""));
				if (strLine.contains("upper-left X:"))
					ulX=Double.parseDouble(strLine.replace("upper-left X:",""));
				if (strLine.contains("upper-left Y:"))
					ulY=Double.parseDouble(strLine.replace("upper-left Y:",""));
				if (strLine.contains("X scale:"))
					xScale=Double.parseDouble(strLine.replace("X scale:",""));
				if (strLine.contains("Y scale:")){
					yScale=Double.parseDouble(strLine.replace("Y scale:",""));
					finished=true;
				}				
			}
			//System.out.println("width:"+width+" height:"+height+" ulX:"+ulX+" ulY:"+ulY+" xScale:"+xScale+" yScale:"+yScale);
			in.close();
		} catch (Exception e) {
			System.err.println("Meta Retriever Error: " + e.getMessage());
		}
		

		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
		}
		(new File("c:\\tmpMap.jpg")).deleteOnExit();
		(new File("c:\\tmpMeta.txt")).deleteOnExit();
		(new File("c:\\tmpBat.bat")).deleteOnExit();
	}

	public double getWidth() {
		return width;
	}

	public double getHeight() {
		return height;
	}

	public double getUlX() {
		return ulX;
	}

	public double getUlY() {
		return ulY;
	}

	public double getxScale() {
		return xScale;
	}

	public double getyScale() {
		return yScale;
	}
}
